package top.cardone.controller;

import com.google.code.kaptcha.Constants;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.web.support.WebSupport;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Created by cardone-home-001 on 2016/1/4.
 */
@Log4j2
@Controller("top.cardone.controller.Controller")
public class CommonController {
    /**
     * 所有json文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/**/*.json")
    @ResponseBody
    public Object allJson(HttpServletRequest request) throws IOException {
        return ApplicationContextHolder.getBean(WebSupport.class).func(request, !log.isDebugEnabled());
    }

    @RequestMapping(value = {"/verifyCode.jpg"})
    public void loginValidationCode(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        final String verifyCode = ApplicationContextHolder.getBean(com.google.code.kaptcha.Producer.class).createText();

        SecurityUtils.getSubject().getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, verifyCode);

        final BufferedImage bi = ApplicationContextHolder.getBean(com.google.code.kaptcha.Producer.class).createImage(verifyCode);

        try (java.io.OutputStream out = response.getOutputStream()) {
            ImageIO.write(bi, "jpg", out);

            out.flush();
        }
    }
}